const express = require("express")
const Joi = require("@hapi/joi")
const expJWT = require("express-jwt")
const config = require('./config')
const app = express()
const path = require('path')
const jwt = require('jsonwebtoken')

app.use(express.static(path.join(__dirname, 'public')))
console.log('xxxxxxxxxxx', path.join(__dirname, 'public'))
app.use(express.urlencoded({ extended: false }))
app.use(express.json())

app.use(expJWT({ secret: config.jwtKey, algorithms: ['HS256'] }).unless({ path: ['/api/login', '/api/register', '/api/getData', '/api/test'] }))


app.use("/api/register", require("./router/register"))
app.use("/api/login", require("./router/login"))
app.use("/api/personal", require("./router/personal"))

app.use("/api/getData", require("./router/getData"))

app.get('/api/test', (req,res)=>{
  const token = jwt.sign({ username: req.body.username}, config.jwtKey, { expiresIn: '1h' }) 
  console.log(res);
  res.send({
    "code": 200,
    "message": "SUCCESS",
    "data": {
      "companyName": "MarketUP",
      "cellphone": "15295790581",
      "officialWebsite": "www.bagevent.com",
      "address": "啊打发",
      "fax": null,
      "squareLogo": "https://static.marketup.cn/resource/marketup/FQINEEPHI0LZAHL15/e5e25814794243e4bf417ee9eb0007e1.png",
      "slogan": null,
      "greet": null,
      "themeColor": "#ff7323"
    },
    "token":  token
  })
})

app.use((err, req, res, next) => {
  console.log(111111111111, err.name)
  if (err instanceof Joi.ValidationError) {
    return res.send({
      status: 1,
      msg: [err.details[0].context.label, err.details[0].message]
    })
  }
  if (err.name === 'UnauthorizedError') {
    return res.send({
      status: 1,
      msg: 'ERROR TOKEN'
    })
  }
  res.send({
    status: 1,
    msg: err.message || err
  })
})
var ws = require("nodejs-websocket");
const { log } = require("console")
console.log("开始建立连接...")

var server = ws.createServer(function (conn) {
  conn.on("text", function (str) {
    console.log("message:" + str)
    conn.sendText("My name is garvin");
  })
  conn.on("close", function (code, reason) {
    console.log("关闭连接")
  });
  conn.on("error", function (code, reason) {
    console.log("异常关闭")
  });
}).listen(8001)
console.log("WebSocket建立完毕")

app.listen(8888, () => console.log("server on http://localhost:8888"))